import { routes } from './routes'
import nprogress from "./progress"
import { components, scaffold } from './components'
import { useMenuStore } from '@/store'

import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
  routes: routes,
  history: createWebHashHistory(),
})

router.beforeEach((to, from, next) => {
  nprogress.start()
  const title = to.meta.title as string
  sessionStorage.setItem('beforePath', from.fullPath)
  document.title = title ? `${title}` : '学习'
  const token = localStorage.getItem('token')
  if (!token && to.path.indexOf('/login') === -1) {
    const formPath = encodeURIComponent(from.fullPath)
    next(`/login?path=${formPath}`);
  } else {
    if (!sessionStorage.getItem('menu-router') && token) useMenuStore().GET_MENU(true)
    next();
  }
})


router.afterEach((to) => {
  nprogress.done()
  const route: any = { path: to.path, meta: to.meta, params: to.params, query: to.query }
  sessionStorage.setItem('route', JSON.stringify(route))
})

export { router, components, scaffold }

